package com.grechur.wanandroidcompose.widget

import android.util.Base64
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.grechur.wanandroidcompose.bean.navi.NavigationBean
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun NaviItemLayout(
    modifier: Modifier = Modifier,
    navigationBean: NavigationBean,
    globalNavHostController: NavHostController,
) {
    navigationBean.articles.takeIf { !it.isNullOrEmpty() }?.let { articles ->
        Column(modifier = modifier
            .background(color = Color.White, shape = RoundedCornerShape(8.dp))) {
            Text(text = "${navigationBean.name}")
            Divider()
            FlowRow() {
                articles.forEach { article ->
                    val link = article.link ?: ""
                    val encode = Base64.encodeToString(link.toByteArray(), Base64.NO_WRAP)
                    Button(onClick = {
                        globalNavHostController.navigate("webView?url=${encode}?name=${article.title}")
                    },
                        modifier = Modifier.padding(end = 5.dp),
                        colors = ButtonDefaults.buttonColors(backgroundColor = Color.White,
                            contentColorFor(backgroundColor = Color.Black))) {
                        Text(text = "${article.title}",
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis)
                    }
                }

            }
        }
    }
}